package cn.itcast.mybatis.first;


import cn.itcast.mybatis.po.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;

import java.io.InputStream;
import java.util.Date;
import java.util.List;

public class MybatisFirst {
    private SqlSessionFactory sqlSessionFactory =null;

    @Before
    public void  init () throws Exception{
        String resource = "SqlMapConfig.xml";

    //第二部加载配置文件
        InputStream inputStream = Resources.getResourceAsStream(resource);
    //第三部创建sqlsessionFactory对象
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);


    }
    @Test
    public void testFindUserById() throws Exception{

        //创建sqlSession回话
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //使用sqlSession查询用户
        User user = sqlSession.selectOne("test.findUserById", 1);
        System.out.println(user);
        sqlSession.close();
    }
    @Test
    public void testFindUserByName() throws Exception{


        //创建sqlSession回话
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //使用sqlSession查询用户

        List<User>list = sqlSession.selectList("test.findUserByName", "张");
        System.out.println(list);
        sqlSession.close();
    }
    @Test
    public void addUser()throws  Exception{
        SqlSession sqlSession = sqlSessionFactory.openSession();
        User user = new User();
        user.setUsername("小乔");
        user.setBirthday(new Date());
        user.setSex("女");
        user.setAddress("上海");
       sqlSession.insert("insertUser",user);
       sqlSession.commit();
        System.out.println(user.getId());
       sqlSession.close();
    }
    @Test
    public void deleteUser()throws Exception{
        SqlSession sqlSession = sqlSessionFactory.openSession();
    sqlSession.delete("deleteUser",27);
    sqlSession.commit();
    sqlSession.close();
    }
    @Test
    public void updateUser()throws Exception{
        SqlSession sqlSession = sqlSessionFactory.openSession();
        User user = new User();
        user.setUsername("吕布");
        sqlSession.update("updateUser",user);
        sqlSession.commit();
        sqlSession.close();
    }
}
